<template>
  <input
    :placeholder="scanStatus.code === 0 ? '请扫码' : '请聚焦后扫码'"
    @blur="handleCardScanBlur"
    @focus="onFocus"
    ref="cardScannerDom"
  />
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, reactive, ref } from "vue";
import { IQRCodeInfo } from "@/model/IQRCodeInfo";
import { ElMessage } from "element-plus";
defineOptions({
  name: "CardScan",
});
/**-------------------------扫码枪----------------------- */
const scanStatus = reactive({
  code: 1,
  message: "不可扫码",
});
const handleCardScanBlur = () => {
  scanStatus.code = 1;
  scanStatus.message = "失焦，不可扫码";
};
const onFocus = () => {
  scanStatus.message = "聚焦，可扫码";
  scanStatus.code = 0;
};

// TODO:扫码枪功能
const cardScannerDom = ref<any>(null);
// const { cardString } = useCardScanner(cardScannerDom);
const handleKeypress = (e) => {
  console.log(e);
  if (e.key === "Enter") {
    console.log(e.key);
    if (cardScannerDom.value.value) {
      handleCardScan(cardScannerDom.value.value);
      cardScannerDom.value.value = "";
    }
  }
};
onMounted(() => {
  console.log(cardScannerDom.value);
  cardScannerDom.value.addEventListener("keypress", handleKeypress);
});
onUnmounted(() => {
  cardScannerDom.value.removeEventListener("keypress", handleKeypress);
  // cardScannerInstance.destroy()
});
const emit = defineEmits(["scanSuccess"]);
// watch(cardString, (newString) => {
//   if (newString) {
//     console.log(newString);
//     // TODO:扫码后的处理
//     // const userString = newString.split(",")
//     handleCardScan(newString);
//   }
// });

const handleMockCardScan = () => {
  handleCardScan("");
};

// 扫码事件完成后的回调
const handleCardScan = (scanString: string | undefined) => {
  if (!scanString) {
    emit("scanSuccess", {});
  } else {
    try {
      // const str = Buffer.from(scanString, "base64").toString();

      console.log("扫码得到的数据", scanString);
      // console.log("base64解码数据", str);
      const scanObj: IQRCodeInfo = JSON.parse(scanString);
      emit("scanSuccess", scanObj);
    } catch (error) {
      ElMessage.error("扫码失败");
      console.log(error);
    }
  }
};
</script>

<style scoped></style>
